#include "WebSocketClient.h"
#include <QDebug>

WebSocketClient::WebSocketClient(QObject *parent) : QObject(parent)
{
    connect(&m_webSocket, &QWebSocket::connected, this, &WebSocketClient::onConnected);
    connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &WebSocketClient::onTextMessageReceived);
    connect(&m_webSocket, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error), this, &WebSocketClient::onError);
}

/**
 * @brief WebSocketClient::onConnected 连接成功后发送内容
 */
void WebSocketClient::onConnected()
{
    statusCnt = true;
    qDebug() << "WebSocket connected";
    sendMessage("Hello, WebSocket Server!");
}

void WebSocketClient::onTextMessageReceived(const QString &message)
{
    qDebug() << "Message received:" << message;
}

void WebSocketClient::onError(QAbstractSocket::SocketError error)
{
    statusCnt = false;
    Q_UNUSED(error);
    qDebug() << "WebSocket error:" << m_webSocket.errorString();
}

void WebSocketClient::sendMessage(const QString &message)
{
    m_webSocket.sendTextMessage(message);
}

bool WebSocketClient::isConnect()
{
    return statusCnt;
}
